import React, { useState, useRef, KeyboardEvent } from 'react'
import { Send, Mic, MicOff } from 'lucide-react'

interface ChatInputProps {
  onSend: (message: string) => void
  disabled?: boolean
  isRecording?: boolean
  onRecordingChange?: (recording: boolean) => void
}

export const ChatInput: React.FC<ChatInputProps> = ({ 
  onSend, 
  disabled = false, 
  isRecording = false, 
  onRecordingChange 
}) => {
  const [message, setMessage] = useState('')
  const textareaRef = useRef<HTMLTextAreaElement>(null)

  const handleSend = () => {
    if (message.trim() && !disabled) {
      onSend(message)
      setMessage('')
      // 重置textarea高度
      if (textareaRef.current) {
        textareaRef.current.style.height = 'auto'
      }
    }
  }

  const toggleRecording = () => {
    if (onRecordingChange) {
      onRecordingChange(!isRecording)
    }
  }

  const handleKeyPress = (e: KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSend()
    }
  }

  const handleInput = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setMessage(e.target.value)
    
    // 自动调整高度
    const textarea = e.target
    textarea.style.height = 'auto'
    textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'
  }
  return (
    <div className="px-4 py-3">
      <div className="flex items-center gap-3 bg-gray-50 rounded-2xl px-4 py-3 text-sm">
        <textarea
          ref={textareaRef}
          value={message}
          onChange={handleInput}
          onKeyPress={handleKeyPress}
          placeholder={isRecording ? "正在录音中..." : "输入您的问题"}
          disabled={disabled || isRecording}
          className="flex-1 resize-none bg-transparent border-none outline-none placeholder-gray-400 text-gray-900 disabled:cursor-not-allowed min-h-[24px] max-h-[120px] leading-6 text-sm"
          rows={1}
        />
        
        {/* 录音按钮 */}
        <button
          onClick={toggleRecording}
          disabled={disabled}
          className={`flex items-center justify-center w-8 h-8 rounded-lg transition-colors flex-shrink-0 ${
        isRecording 
          ? 'bg-red-500 hover:bg-red-600 animate-pulse' 
          : 'bg-gray-400 hover:bg-gray-500'
          } disabled:bg-gray-300 disabled:cursor-not-allowed`}
          title={isRecording ? "停止录音" : "开始录音"}
        >
          {isRecording ? (
        <MicOff className="w-4 h-4 text-white" />
          ) : (
        <Mic className="w-4 h-4 text-white" />
          )}
        </button>
        
        {/* 发送按钮 */}
        <button
          onClick={handleSend}
          disabled={disabled || !message.trim() || isRecording}
          className="flex items-center justify-center w-8 h-8 bg-[#F6B610] hover:bg-[#F6B610] disabled:bg-gray-300 disabled:cursor-not-allowed rounded-lg transition-colors flex-shrink-0"
        >
          <Send className="w-4 h-4 text-white" />
        </button>
      </div>
    </div>
  )
}
